let express = require('express');
let bodyParser = require('body-parser');
let session = require('express-session');
let printLog = require('./log4j-config');
let sequlize = require('./sequlize-config');
let writeSession = require('./http/session');
let addOneActivity = require('./http/addActivity');
let { getAllActivity, getThisWeekActivity, todayHasActvity } = require('./http/getActivity');
let deleteActivityByAid = require('./http/deleteActivity');
let addOneParticipant = require('./http/addParticipant');
let app = express();
//app.use(compression());
// app.use(cookieParser('admin'));
app.use(session({
    secret: 'admin',
    saveUninitialized: false,
    resave: false,  // 是否每次都重新保存会话，建议false
    cookie: {
        maxAge: 1800000 // 有效期，单位是毫秒
    }
}));
//利用bodyParser解析请求体的内容
//post
app.use(bodyParser.json());
//get
app.use(bodyParser.urlencoded({ extended: true }));
//把所有请求的跨域问题都在中间件的部分处理
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    if (req.method == 'OPTIONS') {
        res.send(200);
    }
    else {
        next();
    }
});
app.use(['/api/activities/add','/api/activities/get/all','/api/activities/delete/:aid' ], function(req, res, next) {
    if(req.session.validate === 'validate') {
        next();
    }
    else {
        printLog.ERROR('no power or session overdue IP : ' + req.host);
        res.status(401).send({succeed : false, validate : false, msg : 'no power'}).end();
    }

})
//错误处理中间件，捕获所有中间件中抛出的错误
app.use(function (err, req, res, next) {
    printLog.ERROR('an error on middleware parse at IP : ' + req.host);
    res.status(err.status || 400).send(JSON.stringify(err)).end();
})
//发布一个活动
app.post('/api/activities/add', function (req, res) {
    addOneActivity(req, res);
});
//报名一个活动
app.post('/api/participant/add', function (req, res) {
    addOneParticipant(req, res);
});
//获取本周所有的活动
app.get('/api/activities/get/thisWeek', function (req, res) {
    getThisWeekActivity(req, res);
});
//获取今日的活动
// app.get('/api/activities/get/today', function (req, res) {
//     todayHasActvity(req, res);
// });
//删除一条已有的活动
app.delete('/api/activities/delete/:aid', function (req, res) {
    deleteActivityByAid(req, res);
});
//权限验证
app.post('/api/secure/identify', function (req, res) {
    writeSession(req, res);

})
app.get('/api/activities/get/all', function (req, res) {
    getAllActivity(req, res);
});
var server = app.listen(1111, function () {
    var port = server.address().port;
    printLog.INFO('___server___start___at' + ":" + port);
});